import {
  EditOutlined,
  ExclamationCircleOutlined,
  LeftOutlined,
} from "@ant-design/icons";
import { useDebounceEffect, useKeyPress, useRequest } from "ahooks";
import { Button, Input, Modal, Space, Typography } from "antd";
import React, { ChangeEvent, useState } from "react";
import { useDispatch } from "react-redux";
import { useNavigate, useParams } from "react-router-dom";
import useGetComponentInfo from "../../../hooks/useGetComponentInfo";
import useGetPageInfo from "../../../hooks/useGetPageInfo";
import { MANAGE_LIST_PATHNAME, QUESTION_STAT_PATHNAME } from "../../../router";
import { updateQuestionService } from "../../../services/question";
import { changePageTitle } from "../../../store/pageInfoReducer";
import styles from "./EditHeader.module.scss";
import EditToolbar from "./EditToolbar";

const TitleElem: React.FC = () => {
  const dispatch = useDispatch();
  const [editState, setEditState] = useState(false);
  const { title, isPublished } = useGetPageInfo();

  function handleChangeTitle(event: ChangeEvent<HTMLInputElement>) {
    const newTitle = event.target.value.trim();
    if (newTitle) dispatch(changePageTitle(newTitle));
  }

  if (editState)
    return (
      <Input
        autoFocus
        defaultValue={title}
        onChange={handleChangeTitle}
        onBlur={() => setEditState(false)}
        onPressEnter={() => setEditState(false)}
        disabled={isPublished}
        allowClear
      />
    );

  return (
    <Space>
      <Typography.Title>{title}</Typography.Title>
      <Button
        type="text"
        shape="circle"
        icon={<EditOutlined />}
        onClick={() => setEditState(true)}
        disabled={isPublished}
      />
    </Space>
  );
};

const SaveButton: React.FC = () => {
  const { id } = useParams();
  const { componentList = [] } = useGetComponentInfo();
  const { title, isPrompt, desc } = useGetPageInfo();
  const { loading, run } = useRequest(
    async () => {
      if (!id) return;
      await updateQuestionService(id, { title, isPrompt, desc, componentList });
    },
    {
      manual: true,
      debounceWait: 500,
    }
  );

  useKeyPress(["ctrl.s", "meta.s"], (event: KeyboardEvent) => {
    event.preventDefault();
    if (!loading) run();
  });

  useDebounceEffect(
    () => {
      if (!loading) run();
    },
    [componentList, title, isPrompt, desc],
    { wait: 4500 }
  );

  return (
    <Button loading={loading} onClick={run} disabled={loading}>
      保存
    </Button>
  );
};

const PublishButton: React.FC = () => {
  const nav = useNavigate();
  const { id } = useParams();
  const { componentList = [] } = useGetComponentInfo();
  const pageInfo = useGetPageInfo();
  const { confirm } = Modal;
  const { loading, run } = useRequest(
    async () => {
      if (!id) return;
      await updateQuestionService(id, {
        ...pageInfo,
        componentList,
        isPublished: !pageInfo.isPublished,
      });
    },
    {
      manual: true,
      onSuccess: async () => {
        if (pageInfo.isPublished) {
          window.location.reload();
        } else {
          nav(QUESTION_STAT_PATHNAME + id);
        }
      },
    }
  );

  function handlePublish() {
    if (pageInfo.isPublished) {
      confirm({
        title: "确定取消发布吗？",
        content: "问卷修改后将会清空答卷，建议复制问卷重新发布",
        icon: <ExclamationCircleOutlined />,
        onOk: () => {
          run();
        },
      });
    } else {
      confirm({
        title: "请确认所有内容都已保存",
        icon: <ExclamationCircleOutlined />,
        onOk: () => {
          run();
        },
      });
    }
  }

  return (
    <Button
      type="primary"
      loading={loading}
      onClick={handlePublish}
      disabled={!componentList.length}
    >
      {pageInfo.isPublished ? "取消发布" : "发布"}
    </Button>
  );
};

const EditHeader: React.FC = () => {
  const nav = useNavigate();
  const { id } = useParams();
  const { isPublished } = useGetPageInfo();
  const { confirm } = Modal;

  function handleGoBack() {
    if (isPublished) {
      nav(MANAGE_LIST_PATHNAME);
    } else {
      confirm({
        title: "确定返回吗？",
        content: "未保存的内容将会丢失",
        icon: <ExclamationCircleOutlined />,
        onOk() {
          nav(MANAGE_LIST_PATHNAME);
        },
      });
    }
  }

  return (
    <div className={styles["header-wrapper"]}>
      <div className={styles.header}>
        <div className={styles.left}>
          <Space>
            <Button type="link" icon={<LeftOutlined />} onClick={handleGoBack}>
              返回
            </Button>
            <TitleElem />
          </Space>
        </div>
        <div className={styles.main}>
          <EditToolbar />
        </div>
        <div className={styles.right}>
          <Space>
            {isPublished ? (
              <Button onClick={() => nav(QUESTION_STAT_PATHNAME + id)}>
                数据统计
              </Button>
            ) : (
              <SaveButton />
            )}
            <PublishButton />
          </Space>
        </div>
      </div>
    </div>
  );
};

export default EditHeader;
